$(document).ready(function() {

    showTab($('.firstTab').attr('id').substring(2));

   $(".headlineElement").click(function() {
     showTab($(this).attr('id').substring(2));
   });
   

 });

var minBodyWidth = 910;

function setBodyMinWidth(){
   var headSize = 0;
   $('.headline').children('.headlineElement').each(function() {
       headSize += $(this).outerWidth( true );
   });
   $('body').css('min-width', Math.max(minBodyWidth, headSize+30));
}

function showTab(id) {
    hideAll();
    var text = $("#h-"+id).text();
    $("#h-"+id).css("background-color","white")
                    .css("border-bottom","1px solid white");
    $(".h-"+id+"-link").remove();
    $("#h-"+id).text(text);
    $("#"+id).css("display","block");
    if(id=='details'){
        minBodyWidth = 910;
    }else if(id=='sequence'){
        minBodyWidth = 910;
    }else if(id=='proteinExpression'){
        minBodyWidth = 1180;
    }else if(id=='sequenceCoverage'){
        minBodyWidth = 910;
    }else if(id=='peptides'){
        minBodyWidth = Math.max($('.peptidesList').width()+70, 910);
    }else if(id=='msmsSpectra'){
        minBodyWidth = Math.max($("#lorikeet table").width()+60, 910);
    }else if(id=='proteinRegulation'){
        minBodyWidth = 950;
    }
    setBodyMinWidth();
}

function hideAll () {
   $(".tab-content").css("display","none");
   $(".headlineElement").css("background-color","#f4fbff")
                 .css("border-bottom","1px solid #ccc");
}

function sequenceCoverageInit(){
    $(".seqCovPlot .peptide").click(function() {
         showTab('msmsSpectra');
    });
    seqCovChangeSize();
    $(window).resize(function() {
         seqCovChangeSize();
    });
}

function seqCovChangeSize() {
    $('.seqCovPlot .experiments').css("width", Math.max($(".tabs").width()-60,770));
    $('.seqCovPlot .experiments .peptides').css("width", $(".seqCovPlot .experiments").width()-170);
    $('.seqCovPlot .reference').css("width", $(".seqCovPlot .experiments").width()-170);
}

function proteinExpressionInit(){
      protExpChangeSize();
      $(window).resize(function() {
         protExpChangeSize();
      });
}

function protExpChangeSize() {
    $('#proteinExpression .plot').css("width", Math.max($(".tabs").width()-550,600));
}

function peptidesInit(){
    var oTable;

    /* Add the events etc before DataTables hides a column */
    $("thead input").keyup( function () {
        /* Filter on the column (the index) of this element */
        oTable.fnFilter( this.value, oTable.oApi._fnVisibleToColumnIndex(
                oTable.fnSettings(), $("thead input").index(this) ) );
    } );

    /*
    * Support functions to provide a little bit of 'user friendlyness' to the textboxes
    */
    $("thead input").each( function (i) {
        this.initVal = this.value;
    } );

    $("thead input").focus( function () {
        if ( this.className == "search_init" )
        {
                this.className = "";
                this.value = "";
        }
    } );

    $("thead input").blur( function (i) {
        if ( this.value == "" )
        {
                this.className = "search_init";
                this.value = this.initVal;
        }
    } );

    oTable = $('#peptidesList').dataTable( {
        "sDom": 'RC<"clear">lfrtip',
        "aoColumnDefs": [
                {"bVisible": false, "aTargets": [ 2, 3, 5, 6, 7, 9 ]}
        ],
        "bInfo": false,
        "bPaginate": false,
        "bSortCellsTop": true,
        "sScrollY": "580"
    } );

    

    minBodyWidth = $('.dataTables_scrollHead').width()+90;
    setBodyMinWidth();

    $(".peptideTable a").click(function() {
       showTab('msmsSpectra');
    });
}

function showHideColumn( iCol ){
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#peptidesList').dataTable();

    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
    minBodyWidth = $('.dataTables_scrollHead').width()+90;
    setBodyMinWidth();
    $(".selectColumns input[name='col"+iCol+"']").attr('checked', bVis ? false : true );
}

function msmsSpectraInit(){
      $("#msPeptide").chained("#msProject");
      $("#msCls").chained("#msPeptide");
      $("#msCellline").chained("#msCls");
      $("#msRawFile").chained("#msCellline");
      $("#msScore").chained("#msRawFile");


      $("#showLorikeetButton").click();
      $("#msScore").change(function () {
          $("#showLorikeetButton").click();
          disableOneSelections();
      });
      disableOneSelections();
}

function lorikeetInit(){
    $("input[name='massTypeOpt']")[0].click();
    minBodyWidth = $("#lorikeet table").width()+60;
    setBodyMinWidth();
}

function regulationInit(){
    $('.cellline input').click(function() {
       if(! $(this).is(':checked')){
           if( $(this).attr('id') == $('#refLine').attr('value')){
               $('.cellline .reference').parent('.cellline').css('background-color', '');
               $('.cellline .reference').removeClass('reference')
                              .addClass('nonreference')
               $('.cellline .refavg')
                          .addClass('reference')
                          .removeClass('nonreference');
               $('.cellline .refavg').parent('.cellline').css('background-color', '#c6dfff');
               $('#refLine').attr('value','avg');
           }
       }
       checkNrOfCelllines();
   });

    $('.cellline .nonreference').click(function() {
       var $sel = ($(this).attr('id')).replace(' ', '_');
       if($('.cellline input[id='+$sel+']').is(':checked')||($sel=='avg')){
           $('.cellline .reference').parent('.cellline').css('background-color', '');
           $('.cellline .reference').removeClass('reference')
                          .addClass('nonreference');
           $('.cellline .ref'+$sel.toLowerCase()).parent('.cellline').css('background-color', '#c6dfff');
           $('.cellline .ref'+$sel.toLowerCase())
                      .addClass('reference')
                      .removeClass('nonreference');
           $('#refLine').attr('value',$sel);
       }
    });

    $('#proteinRegulation .noDummyButton').click(function() {
        displayLoading();
        activateRegulationButton(false);
    });

    $('.refavg').click();
    $('#proteinRegulation .search').click();
}

function selectAllCls(){
    $('.cellline input[type=checkbox]').each(function(){
        if(!$(this).is(':checked')){
            $(this).click();
        }
    });
}

function selectNoneCls(){
    $('.cellline input[type=checkbox]').each(function(){
        if($(this).is(':checked')){
            $(this).click();
        }
    });
}

function checkNrOfCelllines(){
    var nrOfChecked = $('.cellline input:checked').size();
    var isActive = true;
    if(nrOfChecked<=1){
        isActive=false;
    }
    activateRegulationButton(isActive);
}

function activateRegulationButton(isActive){
    if(isActive){
        $("#proteinRegulation input[type='submit']").css("display", "block");
        $("#proteinRegulation .dummy").css("display", "none");
    }else{
        $("#proteinRegulation input[type='submit']").css("display", "none");
        $("#proteinRegulation .dummy").css("display", "block");
    }
}

function showLoadingCursor(isLoading){
    if(isLoading){
        $('body').css('cursor', 'progress');
        $('#proteinRegulation .updatePlot').css('cursor', 'progress');
    }else{
        $('body').css('cursor', '');
    }
}

function regulationPlotInit(){
    checkNrOfCelllines();
    showLoadingCursor(false);
    $('#proteinRegulation .updatePlot').click(function() {
        if($('.updatingPlots').children().size()==0){
            activateRegulationButton(false);
            $('.updatingPlots').html('<div class="loading">Loading...</div>');
            showLoadingCursor(true);
            var celName = $(this).children('.celllineR').attr('celllineName');
            if(!$('.cellline input[id='+celName+']').is(':checked')){
                $('.cellline input[id='+celName+']').click();
            }
            $('.cellline .ref'+celName.toLowerCase()).click();
            $('#proteinRegulation #regulationResults #refLine').attr('value', celName);
            $('#proteinRegulation #regulationResults .updatePlotButton').click();
        }
    });
}

function displayLoading() {
    showLoadingCursor(true);
    $("#regulationResults").html('<div class="loading">Loading...</div>');
}

function showSelected() {
    hideAllMarked();
    showAllSelected();
}

function showAllSelected() {
    var $col = $('.legend .peptide .color').css('background-color');
    $(".selected").each(function ($i) {
        var $curId = $(this).attr('id');
        $('.'+$curId).css('background-color',$col);
    })
}

function hideAllMarked() {
    $(".marked").css('background-color','white');
}

function selectProject($id) {
    if($('#proj'+$id).hasClass('nonselected')){
        $('#proj'+$id+' .title').text('Hide');
        $('#proj'+$id).removeClass('nonselected')
                      .addClass('selected');
        $('#proj'+$id+' #'+$id).attr('checked', true);
    }else{
        $('#proj'+$id+' .title').text('Show');
        $('#proj'+$id).removeClass('selected')
                      .addClass('nonselected');
        $('#proj'+$id+' #'+$id).attr('checked', false);
    }
    hideAllMarked();
    showAllSelected();
}

function hoverSelected($id) {
    $('#sequence .seq .proj'+$id).css('background-color','#96CAFF');
    $('#sequence .projects #proj'+$id).css('background-color','#96CAFF');
}

function hoverOutSelected() {
    hideAllMarked();
    showAllSelected();
    resetHover();
}
function resetHover() {
    $('#sequence .projects .ele').css('background-color','white');
}

function changeColor(type) {
    if(type=='intensity'){
        $('.peptide').each(function (){
            var intensity=$(this).attr('intensity')
            if(intensity>240){
                intensity=240;
            }else if(intensity<0){
                intensity=0;
            }

           this.style.backgroundColor='hsl('+(240-$(this).attr('intensity'))+', 100%, 50%)';
        });
        $('.changeColor input[value=intensity]').attr("checked", "checked");
        $('.colorScale').css('display','inline-block');
        $('.uniqScale').css('display','none');
    }else if(type=='uniqueness'){
        $('.peptide').each(function (){
           this.style.backgroundColor='';
        });
        $('.changeColor input[value=uniqueness]').attr("checked", "checked");
        $('.colorScale').css('display','none');
        $('.uniqScale').css('display','inline-block');
    }
}

function resizeTabContent(){
    var size = $(".peptidesList").width();
    if(size>1490){
        $('#peptides').width(size+40);
        $('.tabs').width(size+40);
    }
}

function resizeMsTab(){
    var size = $("#lorikeet table").width();
    $(".tabs").css('min-width', size+40);
}

function disableOneSelections(){
    $(".msSelection select").each(function() {
        if($(this).children().size()==1){
            $(this).attr('disabled', '');
        }
    });
}

function showZero(projectId){
    if($('#expressionFor'+projectId+' .nullLine').css('display')=='none'){
        $('#expressionFor'+projectId+' .showZeroExpression .button').text('Hide Missing');
        $('#expressionFor'+projectId+' .nullLine').css('display', 'block');
        var listHeight = $('#expressionFor'+projectId+' .plot #list').attr('wn')*24;
        $('#expressionFor'+projectId+' .plot #list').css('height',listHeight);
        $('#expressionFor'+projectId+' .plot #list .cls').each(function(){
            var topPos = $(this).attr('wnp')*1;
            var height = $(this).attr('wns')*24;
            $(this).css('top', topPos);
            $(this).css('height', height);
        });
        $('#expressionFor'+projectId+' .plot #list .cls .line').each(function(){
            var topPos = $(this).attr('wn')*24;
            $(this).css('top', topPos);
        });
    }else{
        $('#expressionFor'+projectId+' .showZeroExpression .button').text('Show All');
        $('#expressionFor'+projectId+' .nullLine').css('display', 'none');
        var listHeight = $('#expressionFor'+projectId+' .plot #list').attr('nn')*24;
        $('#expressionFor'+projectId+' .plot #list').css('height',listHeight);
        $('#expressionFor'+projectId+' .plot #list .cls').each(function(){
            var topPos = $(this).attr('nnp');
            var height = $(this).attr('nns')*24;
            $(this).css('top', topPos+'px');
            $(this).css('height', height+'px');
        });
        $('#expressionFor'+projectId+' .plot #list .cls .line').each(function(){
            var topPos = $(this).attr('nn')*24;
            $(this).css('top', topPos);
        });
    }
}